using System;
using System.Collections;
using System.Xml;
using System.Reflection;
using System.Text;
using System.IO;
using System.Net;
using System.Threading;
using System.Security.Principal;
using InfoJetSoft.Service.Entity;
using InfoJetSoft.Service.Util;

namespace InfoJetSoft.Service.Worker
{
	/// <summary>
	/// Summary description for DataObjectWSQueryLoader.
	/// </summary>
	class DataObjectWSQueryWorker
	{

		public static void queryDoc( Form form, DataWSAdapter wsAdapter )
		{
			UnauthorizedConnection loginConnection = DataWebUnauthorizedWorker.findLoginConnection( form, wsAdapter );
			queryDoc( form, wsAdapter, loginConnection );
		}

		public static void queryDoc( Form form, DataWSAdapter wsAdapter , UnauthorizedConnection loginConnection )
		{
			XmlDocument requestSoapDoc = DataObjectWSUtil.buildSoapRequestDoc( wsAdapter, form.XmlDoc, form.XmlNsResolver );
			
			HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create( wsAdapter.ServiceUrl );
			request.Headers.Add("SOAPAction", wsAdapter.SoapAction );
            //CID 0868 //2010.01.05 //Begin
            if (form.JetContext.WebServiceCookie != null)
            {
                request.Headers.Add("cookie", form.JetContext.WebServiceCookie);
            }
            //CID 0868 //2010.01.05 //End
			request.ContentType = "text/xml;charset=\"utf-8\"";
			request.Accept = "text/xml";
			request.Method = "POST";
			request.PreAuthenticate = true;
            //CID 0808 //2011.03.02 //Begin
            //CID 0870 //2011.04.13 //Begin
            WindowsImpersonationContext impContext = null;
            if (ConfigUtil.EnableWSImpersonation())
            {
                WindowsIdentity winId = (WindowsIdentity)form.HttpContext.User.Identity;
                impContext = winId.Impersonate();
            }
            //CID 0870 //2011.04.13 //End
            //CID 0035 //2008.06.30 //Begin
            if (form.JetContext.WebServiceCredentials != null)
            {
                request.Credentials = form.JetContext.WebServiceCredentials;
            }
            else
            {
                //CID 0370 //2009.07.17 //Begin
                request.Credentials = DataWebUnauthorizedWorker.getCredentialCache(form.HttpContext, new Uri(wsAdapter.ServiceUrl), loginConnection);
                //CID 0370 //2009.07.17 //End
            }
            //CID 0808 //2011.03.02 //End
            //CID 0941 //2011.06.05 //Begin
            if (wsAdapter.Timeout >= 0)
            {
                request.Timeout = wsAdapter.Timeout * 1000;
            }
            //CID 0941 //2011.06.05 //End
            //CID 0962 //2011.06.27 //Begin
            int webTimeout = ConfigUtil.WebTimeout();
            if (webTimeout >= 0)
            {
                request.Timeout = webTimeout;
            }
            //CID 0962 //2011.06.27 //End
			Stream requestStream = request.GetRequestStream();
			byte[] content = System.Text.UTF8Encoding.UTF8.GetBytes( requestSoapDoc.OuterXml );
			requestStream.Write( content, 0, content.Length );
			requestStream.Close();

			HttpWebResponse response = (HttpWebResponse)request.GetResponse();
			Stream responseStream = response.GetResponseStream();
			StreamReader reader = new StreamReader(responseStream);
			string xml = reader.ReadToEnd();
            //CID 0870 //2011.04.13 //Begin
            HttpStatusCode statusCode = response.StatusCode;
            response.Close();
            //CID 1091 //2012.02.10 //Begin
            reader.Close();
            //CID 1091 //2012.02.10 //End
            if (impContext != null)
            {
                impContext.Undo();
            }
            //CID 0870 //2011.04.13 //End

			XmlDocument responseDoc = new XmlDocument();
			responseDoc.LoadXml( xml );
			NamespaceResolver responseNsResolver = new NamespaceResolver( responseDoc );

			XmlElement dataFieldsElement = DataObjectWSUtil.setSoapResponseDoc( wsAdapter, form.XmlDoc, form.XmlNsResolver, responseDoc, responseNsResolver );

            if ((statusCode == HttpStatusCode.OK) || (statusCode == HttpStatusCode.Created))
			{
				if( form.HttpContext.Session != null )
				{
					form.HttpContext.Session[ wsAdapter.Id ] = loginConnection;
				}
			}

            //CID 1148 //2012.03.28 //Begin 
            FormBuildFieldListByXMLDocWorker.buildFieldListByXMLDoc(form, true);
            FormCalculatedFieldWorker.calcaulteGroupNode(form, dataFieldsElement, null, false);
            //CID 0907 //2011.05.13 //End
            //CID 0473 //2009.12.14 //End
            string path = DOMUtil.getNodePath(dataFieldsElement);
            FormCodeDispatchWorker.OnAfterChange(form, path, dataFieldsElement, FormCodeDispatchWorker.Updated, false);
            //CID 1148 //2012.03.28 //End
		}

	}
}
